package com.top.ruizhong.main.access

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.LogUtils
import com.module.lemlin.LoadingDialog
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.tbruyelle.rxpermissions3.RxPermissions
import com.top.ruizhong.R
import com.top.ruizhong.main.host.MainActivity
import com.top.ruizhong.mode.vm.AccessViewModel
import kotlinx.android.synthetic.main.activity_access_2.*

class AccessActivity : ViewModeActivity<AccessViewModel>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, AccessActivity::class.java)
            activity.startActivity(intent)
        }
    }

    private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {
        override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
            super.onFragmentResumed(fm, f)
            if (f is LoginFragment && motionLayout.currentState == R.id.end) {
                motionLayout.transitionToStart()
            }
        }

        override fun onFragmentCreated(
            fm: FragmentManager, f: Fragment, savedInstanceState: Bundle?
        ) {
            super.onFragmentCreated(fm, f, savedInstanceState)
            if (f !is LoginFragment && motionLayout.currentState == R.id.start) {
                motionLayout.transitionToEnd()
            }
        }

    }

    override val layoutResId: Int
        get() = R.layout.activity_access_2

    override fun viewModel(): AccessViewModel {
        return createViewModel()
    }

    override fun initView() {

        supportFragmentManager(
            LoginFragment.newInstance(), isToBackStack = false
        )

        supportFragmentManager.registerFragmentLifecycleCallbacks(
            fragmentLifecycleCallbacks, (true)
        )
    }

    override fun initViewMode() {
        viewModel.userSmsLiveData.observe(this, Observer { response ->
            when (response.status) {
                Status.START -> LoadingDialog.show(
                    this as Context, resId = R.layout.dialog_load_style_1
                )
                Status.FAILURE -> {
                    LoadingDialog.dismiss()
                    toast(response.throwable?.msg ?: "未知错误")
                }
                Status.SUCCESS -> {
                    LoadingDialog.dismiss()
                    toast(response.httpData?.msg ?: "发送成功")
                    response.httpData?.data?.let { any ->
                        if (any !is String)
                            return@Observer
                        supportFragmentManager(CodeFragment.newInstance(any))
                    }
                }
            }
        })


        viewModel.userLoginLiveData.observe(this, Observer { response ->
            when (response.status) {
                Status.START -> LoadingDialog.show(
                    this as Context, resId = R.layout.dialog_load_style_1
                )
                Status.FAILURE -> {
                    LoadingDialog.dismiss()
                    toast(response.throwable?.msg ?: "未知错误")
                }
                Status.SUCCESS -> {
                    LoadingDialog.dismiss()
                    MainActivity.open(activity = this)
                }
            }
        })
    }

    override fun onStop() {
        super.onStop()
        finish()
    }

    private fun supportFragmentManager(fragment: Fragment, isToBackStack: Boolean = true) {
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (isToBackStack) {
            transaction.setCustomAnimations(
                R.animator.slide_right_in, R.animator.slide_left_out,
                R.animator.slide_left_in, R.animator.slide_right_out
            )
            transaction.replace(R.id.frameAccessBody, fragment)
            transaction.addToBackStack(null)
        } else {
            transaction.add(R.id.frameAccessBody, fragment)
        }
        transaction.commit()
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.ivAccessBack -> onBackPressed()
            R.id.ivLoginWxBind -> {
//                supportFragmentManager(CodeFragment.newInstance("18396125445"))
                val rxPermissions = RxPermissions(this)
                rxPermissions.request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO
                ).subscribe {
                    if (!it) {
                        toast("请到设置中开启相关权限")
                    } else {
                        MainActivity.open(activity = this)
                    }
                }
            }
            R.id.tvLoginGetCode -> {
                viewModel.contentMobileLoginLiveData.value?.let {
                    viewModel.userSmsSend(it.toString(), "login")
                }
            }
            R.id.tvBindGetCode -> {
                viewModel.contentMobileBindLiveData.value?.let {
//                    supportFragmentManager(CodeFragment.newInstance(it.toString()))
                    viewModel.userSmsSend(it.toString(), "login")
                }
            }
        }
    }

}